﻿#region Copyright
// Copyright (c) 2011-2012 RaisingForce Team (Alikin Sergey)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Xml;
using System.Xml.Serialization;
using RaisingForce.Raise.ObjectModel;
using RaisingForce.Raise.Properties;

namespace RaisingForce.Raise.Measures
{
    [Serializable]
    public struct Angle :
        IMeasureValue<IAngleMeasure, double, Angle>,
        ISerializable,
        IXmlSerializable
    {
        #region Constructors

        private Angle(DoubleMeasureValue<IAngleMeasure> value)
        {
            Contract.Requires(!value.IsDefault());
            this.value = value;
        }

        public Angle(double measureValue, IAngleMeasure measure)
        {
            if (measure == null)
            {
                throw new ArgumentNullException("measure");
            }
            if (!measure.ValueIsValid(measureValue))
            {
                throw new ArgumentException("measureValue");
            }
            Contract.EndContractBlock();
            this.value = new DoubleMeasureValue<IAngleMeasure>(measureValue, measure);
        }

        #endregion

        #region Private Declarations

        private static readonly AngleProvider provider = AngleProvider.Instance;

        private DoubleMeasureValue<IAngleMeasure> value;

        private DoubleMeasureValue<IAngleMeasure> Value
        {
            get
            {
                Contract.Ensures(!Contract.Result<DoubleMeasureValue<IAngleMeasure>>().IsDefault());
                if (this.value.IsDefault())
                {
                    this.value = provider.Unknown;
                }
                return this.value;
            }
            set
            {
                this.value = value;
            }
        }

        [ContractInvariantMethod]
        private void ObjectInvariant()
        {
            Contract.Invariant(Angle.ValueIsValid(this.Value.InnerValue));
        }

        #endregion

        #region Serialization Declarations

        private Angle(SerializationInfo info, StreamingContext context)
        {
            this.value = provider.SerializationConstructor(info);
        }

        private void setupForSerialization()
        {
            // это выражение нельзя целиком перенести в provider из-за особенностей свойства Value
            // поэтому данная функция должна дублироваться во всех структурах IMeasureValue<,,>
            if (!provider.IsUnknown(this.Value))
            {
                this.Value = provider.GetDefault(this.Value);
            }
        }

        [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            this.setupForSerialization();
            provider.GetSerializationData(info, this.Value);
        }

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            this.Value = provider.ReadXml(reader);
        }

        public void WriteXml(XmlWriter writer)
        {
            this.setupForSerialization();
            provider.WriteXml(writer, this.Value);
        }

        #endregion

        #region Constants

        public const double UnknownValue =
            AngleProvider.UnknownValue;

        public static readonly string UnknownString =
            provider.UnknownString;

        public static readonly Angle Unknown =
            new Angle(provider.Unknown);

        public static readonly Angle Epsilon =
            new Angle(provider.Epsilon);

        public static readonly Angle FullTurn =
            Angle.DefineInDegree(360);

        #endregion

        #region Operators

        public static bool operator ==(Angle first, Angle second)
        {
            return Angle.Equals(first, second);
        }

        public static bool operator !=(Angle first, Angle second)
        {
            return provider.OpInequality(first.Value, second.Value);
        }

        public static bool operator <(Angle first, Angle second)
        {
            return provider.OpLessThan(first.Value, second.Value);
        }

        public static bool operator <=(Angle first, Angle second)
        {
            return provider.OpLessThanOrEqual(first.Value, second.Value);
        }

        public static bool operator >(Angle first, Angle second)
        {
            return provider.OpGreaterThan(first.Value, second.Value);
        }

        public static bool operator >=(Angle first, Angle second)
        {
            return provider.OpGreaterThanOrEqual(first.Value, second.Value);
        }

        public static Angle operator +(Angle first, Angle second)
        {
            return Angle.Add(first, second);
        }

        public static Angle operator -(Angle first, Angle second)
        {
            return Angle.Subtract(first, second);
        }

        public static Angle operator *(Angle first, Angle second)
        {
            return Angle.Multiply(first, second);
        }

        public static Angle operator /(Angle first, Angle second)
        {
            return Angle.Divide(first, second);
        }

        public static Angle operator *(Angle angle, double multiplier)
        {
            Contract.Requires(multiplier > 0);
            return Angle.Multiply(angle, multiplier);
        }

        public static Angle operator *(double multiplier, Angle angle)
        {
            Contract.Requires(multiplier > 0);
            return Angle.Multiply(multiplier, angle);
        }

        public static Angle operator /(Angle angle, double divisor)
        {
            Contract.Requires(divisor > 0);
            return Angle.Divide(angle, divisor);
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Получает угол, нормализованный в интервале [0;360) для градусов и [0;2*PI) для радиан.
        /// </summary>
        /// <returns>Нормализованный угол.</returns>
        [Pure]
        public Angle GetNormalized()
        {
            return new Angle(
                provider.GetNormalized(this.Value));
        }

        #endregion

        #region Base Overrides

        public override bool Equals(object obj)
        {
            return obj is Angle ?
                this.Equals((Angle)obj) :
                false;
        }

        public override int GetHashCode()
        {
            return provider.GetHashCode(this.Value);
        }

        public override string ToString()
        {
            return provider.ToString(
                this.Value,
                format: null,
                formatProvider: null);
        }

        #endregion

        #region IMeasureValue<IAngleMeasure, double, Angle> Members

        public bool IsUnknown
        {
            get
            {
                return provider.IsUnknown(this.Value);
            }
        }

        [Pure]
        public double Get(IAngleMeasure measure)
        {
            return provider.Get(this.Value, measure);
        }

        [Pure]
        public bool Equals(Angle other)
        {
            return provider.Equals(this.Value, other.Value);
        }

        [Pure]
        public int CompareTo(Angle other)
        {
            return provider.CompareTo(this.Value, other.Value);
        }

        [Pure]
        public int CompareTo(object obj)
        {
            return obj is Angle ?
                this.CompareTo((Angle)obj) :
                +1; // по определению любое значение (this) больше, чем null
        }

        [Pure]
        public string ToString(string format)
        {
            return provider.ToString(
                this.Value,
                format: format,
                formatProvider: null);
        }

        [Pure]
        public string ToString(IFormatProvider formatProvider)
        {
            return provider.ToString(
                this.Value,
                format: null,
                formatProvider: formatProvider);
        }

        [Pure]
        public string ToString(
            string format,
            IFormatProvider formatProvider)
        {
            return provider.ToString(
                this.Value,
                format: format,
                formatProvider: formatProvider);
        }

        #endregion

        #region Static Operator Methods

        [Pure]
        public static bool Equals(Angle first, Angle second)
        {
            return provider.OpEquality(first.Value, second.Value);
        }

        [Pure]
        public static int Compare(Angle first, Angle second)
        {
            return provider.CompareTo(first.Value, second.Value);
        }

        [Pure]
        public static Angle Add(Angle first, Angle second)
        {
            return new Angle(
                provider.OpAddition(first.Value, second.Value));
        }

        [Pure]
        public static Angle Subtract(Angle first, Angle second)
        {
            return new Angle(
                provider.OpSubtraction(first.Value, second.Value));
        }

        [Pure]
        public static Angle Multiply(Angle first, Angle second)
        {
            return new Angle(
                provider.OpMultiply(first.Value, second.Value));
        }

        [Pure]
        public static Angle Divide(Angle first, Angle second)
        {
            return new Angle(
                provider.OpDivision(first.Value, second.Value));
        }

        [Pure]
        public static Angle Multiply(Angle angle, double multiplier)
        {
            if (multiplier <= 0)
            {
                throw new ArgumentOutOfRangeException(
                    "multiplier",
                    multiplier,
                    Resources.Exception_ArgumentIsNotPositive);
            }
            Contract.EndContractBlock();
            return new Angle(
                provider.OpMultiply(angle.Value, multiplier));
        }

        [Pure]
        public static Angle Multiply(double multiplier, Angle angle)
        {
            if (multiplier <= 0)
            {
                throw new ArgumentOutOfRangeException(
                    "multiplier",
                    multiplier,
                    Resources.Exception_ArgumentIsNotPositive);
            }
            Contract.EndContractBlock();
            return new Angle(
                provider.OpMultiply(angle.Value, multiplier));
        }

        [Pure]
        public static Angle Divide(Angle angle, double divisor)
        {
            if (divisor <= 0)
            {
                throw new ArgumentOutOfRangeException(
                    "multiplier",
                    divisor,
                    Resources.Exception_ArgumentIsNotPositive);
            }
            Contract.EndContractBlock();
            return new Angle(
                provider.OpDivision(angle.Value, divisor));
        }

        #endregion

        #region Static Methods

        [Pure]
        public static bool ValueIsValid(double measureValue)
        {
            return provider.ValueIsValid(measureValue);
        }

        public static Angle DefineInRadian(double measureValue)
        {
            if (!AngleMeasures.Radian.ValueIsValid(measureValue))
            {
                throw new ArgumentException("measureValue");
            }
            Contract.EndContractBlock();
            return new Angle(measureValue, AngleMeasures.Radian);
        }

        public static Angle DefineInDegree(double measureValue)
        {
            if (!AngleMeasures.Degree.ValueIsValid(measureValue))
            {
                throw new ArgumentException("measureValue");
            }
            Contract.EndContractBlock();
            return new Angle(measureValue, AngleMeasures.Degree);
        }

        #endregion
    }
}
